from zope.interface import implements
from zope.component import adapts, getMultiAdapter, queryUtility
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from Products.CMFPlone.utils import getToolByName

from plonetheme.apkntheme import APKNThemeMessageFactory as _
from plonetheme.apkntheme.settings import COUNTRY_FOLDER_META,\
                                          ANM_FEED_URL,\
                                          ANM_NEWS_URL
from plonetheme.apkntheme.browser.interfaces import IFolderContainerDashboard,\
                                                    IFolderCountryDashboard
from plonetheme.apkntheme.browser.syndication import random_string

from Acquisition import aq_inner, aq_parent
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

COUNTRY_FOLDER_ROOT = '/Plone/apex/country-folders'

class ICountryFeedsPortlet(IPortletDataProvider):
    """
    """
    
class Assignment(base.Assignment):
    implements(ICountryFeedsPortlet)
    
    @property
    def title(self):
        return _('Parliament News')
        
class Renderer(base.Renderer):
    def __init__(self, context, request, view, manager, data):
        base.Renderer.__init__(self, context, request, view, manager, 
        data)
    
    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog', None)
    
    @property
    def is_anonymous(self):
        mtool = getToolByName(self.context, 'portal_membership', None)
        if mtool:
            return bool(mtool.isAnonymousUser())
        return True
    
    @property
    def available(self):
        return self.is_anonymous and \
                    IFolderCountryDashboard.providedBy(self.current_object)\
                    and \
                    self.is_folder_root

    @property
    def portal_url(self):
        return getToolByName(self.context, 'portal_url', None)

    @property
    def current_object(self):
        current_object = aq_inner(self.context)
        current_path = '/'.join(current_object.getPhysicalPath())
        if not (current_path == COUNTRY_FOLDER_ROOT):
            if not IFolderCountryDashboard.providedBy(current_object):
                not_found_root = True
                current_parent = current_object
                while not_found_root:
                    parent_object = aq_parent(current_parent)
                    if IFolderCountryDashboard.providedBy(parent_object):
                        not_found_root = False
                    elif (parent_object == self.portal_url.getPortalObject()):
                        return current_object
                    current_parent = parent_object
                return current_parent
        return current_object

    @property
    def is_folder_root(self):
        return IFolderCountryDashboard.providedBy(self.current_object) \
                and (self.current_object == aq_inner(self.context))

    def getNewsURL(self):
        try:
            country_code = getattr(self.current_object,
                                    u'meta_country_code')
        except AttributeError:
            country_code = u''
        lang_code = u'en'
        news_url = ANM_NEWS_URL %(lang_code, country_code.upper())
        return news_url

    def getFeedData(self):
        feed_data = {}
        try:
            country_code = getattr(self.current_object, u'meta_country_code')
        except AttributeError:
            country_code = u''
        lang_code = u'en'
        country_name = self.current_object.Title()
        rss_url = ANM_FEED_URL %(country_name, lang_code)
        if hasattr(self.current_object, u'meta_feed_source'):
            rss_url = getattr(current_object, u'meta_feed_source') \
            %(country_code, lang_code)
        
        feed_title = _("apkn_rss_feed_title_country_folders",
        default = "${country_name} News Feed - ANM",
        mapping = {u'country_name': country_name})
        
        feed_data['feed_url'] = rss_url
        feed_data['feed_title'] = feed_title
        feed_data['dom_id'] = random_string()
        feed_data['news_url'] = self.getNewsURL()
        return feed_data


    render = ViewPageTemplateFile("countryfeeds.pt")

class AddForm(base.AddForm):
    label = _("Add country feeds portlet")
    description = _("This portlet renders country rss feeds")
    
    def create(self, data):
        return Assignment()

class EditForm(base.EditForm):
    label = _("Edit ocuntry feeds portlet")
    description = _("This portlet renders country rss feeds")
